<template>
  <a-modal v-model="visible" title="签名" :footer="null" width="600px" @cancel="handleCancel">
    <div class="signature-container">
      <canvas ref="signatureCanvas" :width="500" :height="300" class="signature-canvas"></canvas>
      <div class="signature-buttons">
        <a-button @click="clearSignature" type="default">清除</a-button>
        <a-button @click="saveSignature" type="primary">保存签名</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { postAction } from '@/api/manage';

export default {
  name: 'SignImgDialog',
  props: {
    lineWidth: {
      type: Number,
      default: 2
    },
  },
  data() {
    return {
      visible: false,
      context: null,
      isDrawing: false,
      text: "",
      status: 0,
    };
  },
  methods: {
    // 显示签名框
    show(text, status) {
      this.text = text;
      this.status = status
      this.visible = true;
      this.$nextTick(() => {
        this.initCanvas();
      });
    },
    // 初始化画布
    initCanvas() {
      const canvas = this.$refs.signatureCanvas;
      this.context = canvas.getContext('2d');
      this.context.clearRect(0, 0, canvas.width, canvas.height);
      this.context.lineWidth = this.lineWidth;
      this.context.strokeStyle = '#000000';
      this.context.lineCap = 'round';
      this.context.lineJoin = 'round';

      // 绑定事件
      canvas.addEventListener('mousedown', this.handleMouseDown);
      canvas.addEventListener('mousemove', this.handleMouseMove);
      canvas.addEventListener('mouseup', this.handleMouseUp);
      canvas.addEventListener('mouseleave', this.handleMouseUp);
    },
    // 鼠标按下
    handleMouseDown(e) {
      this.isDrawing = true;
      const canvas = this.$refs.signatureCanvas;
      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      this.context.beginPath();
      this.context.moveTo(x, y);
    },
    // 鼠标移动
    handleMouseMove(e) {
      if (!this.isDrawing) return;

      const canvas = this.$refs.signatureCanvas;
      const rect = canvas.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;

      this.context.lineTo(x, y);
      this.context.stroke();
    },
    // 鼠标抬起
    handleMouseUp() {
      this.isDrawing = false;
      this.context.closePath();
    },
    // 清除签名
    clearSignature() {
      const canvas = this.$refs.signatureCanvas;
      this.context.clearRect(0, 0, canvas.width, canvas.height);
    },
    // 保存签名
    saveSignature() {
      const canvas = this.$refs.signatureCanvas;
      // 转换为base64
      const base64 = canvas.toDataURL('image/png');
      // 上传图片
      this.uploadImage(base64);
    },
    // 上传图片
    uploadImage(base64) {
      // 这里使用后端已有的上传图片方法
      // 假设postAction是一个已有的请求方法
      const formData = new FormData();
      // 转换base64为blob
      const blob = this.base64ToBlob(base64);
      formData.append('file', blob, 'signature.png');
      formData.append('text', this.text);

      postAction('/tankerRegistration/tankerRegistration/m/upload', formData).then(res => {
        if (res.success) {
          // 上传成功，返回url
          this.$emit('close', { url: res.message, status: this.status });
          this.visible = false;
        } else {
          this.$message.error('上传失败');
        }
      }).catch(err => {
        this.$message.error('上传失败');
        console.error(err);
      });
    },
    // base64转blob
    base64ToBlob(base64) {
      const parts = base64.split(';base64,');
      const contentType = parts[0].split(':')[1];
      const raw = window.atob(parts[1]);
      const rawLength = raw.length;
      const uInt8Array = new Uint8Array(rawLength);

      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }

      return new Blob([uInt8Array], { type: contentType });
    },
    // 取消
    handleCancel() {
      this.visible = false;
      this.$emit('close', { url: '', status: this.status });
    }
  }
};
</script>

<style scoped>
.signature-container {
  padding: 20px;
}

.signature-canvas {
  border: 1px solid #d9d9d9;
  margin-bottom: 20px;
}

.signature-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>